package org.opens.netty.template;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.nio.charset.Charset;

@Slf4j
public class ServerTemplate {

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup boosEventLoopGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerEventLoopGroup = new NioEventLoopGroup();

        ChannelFuture channelFuture = new ServerBootstrap()
                .group(boosEventLoopGroup, workerEventLoopGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast("handle1", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf data = ((ByteBuf) msg);
                                log.info("server端接受到数据: {}", data.toString(Charset.defaultCharset()));
                                for (int i = 0; i < 10; i++) {
                                    nioSocketChannel.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes(("hi" + i).getBytes()));
                                }
                            }
                        });
                    }
                })
                .bind(8080);

        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.info("server已启动.");
            }
        });

        Channel channel = channelFuture.sync().channel();

        ChannelFuture closeFuture = channel.closeFuture();
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                boosEventLoopGroup.shutdownGracefully();
                workerEventLoopGroup.shutdownGracefully();
                log.info("server已停止.");
            }
        });

        Thread.currentThread().join();
    }

}
